package com.xci.xajtfb._core;

import com.github.lvyanyang.core.BaseService;
import com.github.lvyanyang.core.Const;
import com.github.lvyanyang.core.IUser;
import com.github.lvyanyang.core.XCI;
import com.xci.xajtfb.bus.entity.WxMember;
import com.xci.xajtfb.bus.service.WxMemberService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 吕艳阳 18049047588@qq.com
 * @since 2021-03-03 18:27
 */
@Service
public class XajtfbService extends BaseService {
    @Resource private WxMemberService wxMemberService;

    /**
     * 获取小程序当前用户信息
     */
    public WxMember getCurrentWxMember() {
        HttpServletRequest request = XCI.getRequest();
        if (XCI.isApiRequest()) {
            var userObj = request.getAttribute(Const.USER_TOKEN_MODEL_KEY);
            if (userObj != null) return (WxMember) userObj;

            var tokenModel = coreService.getCurrentToken();
            if (tokenModel != null) {
                WxMember sysUser = wxMemberService.selectById(tokenModel.getValue());
                request.setAttribute(Const.USER_TOKEN_MODEL_KEY, sysUser);
                return sysUser;
            }
            return null;
        }
        var userObj = request.getSession().getAttribute(Const.USER_SESSION_KEY);
        if (userObj != null) {
            return (WxMember) userObj;
        }
        return null;
    }
}
